import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:smartidea_shop/provider/base.dart';
import 'home_sub_view/home_search_view.dart';
import 'home_sub_view.dart';

class HomeView extends StatefulWidget {
  const HomeView({Key? key}) : super(key: key);
  @override
  HomeViewState createState() => HomeViewState();
}

class HomeViewState extends State<HomeView>
    with SingleTickerProviderStateMixin, RestorationMixin {
  final RestorableInt tabIndex = RestorableInt(0);
  late TabController _tabController;
  List<String> tabs = [];
  List<HomepageSubpage> pages = [];
  List<Tab> tabViews = [];
  var topBarHeight = 65;

  @override
  String get restorationId => 'tab_scrollable_demo';

  @override
  void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
    registerForRestoration(tabIndex, 'tab_index');
    _tabController.index = tabIndex.value;
  }

  @override
  void initState() {
    tabs = ["推荐", "运动新品", "服装配饰", "家具日用", "科技数码", "抗疫", "免费小说", "热点"];
    _tabController = TabController(
      initialIndex: 0,
      length: tabs.length,
      vsync: this,
    );
    _tabController.addListener(() {
      // When the tab controller's value is updated, make sure to update the
      // tab index value, which is state restorable.
      setState(() {
        tabIndex.value = _tabController.index;
      });
    });

    for (int i = 0; i < tabs.length; i++) {
      pages.add(HomepageSubpage());
      tabViews.add(Tab(text: tabs[i]));
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    String loginToken =
        Provider.of<BaseProvider>(context, listen: false).state.loginToken!;
    return Scaffold(
        body: Container(
      child: Stack(
        children: [
          Container(
            width: MediaQuery.of(context).size.width,
            color: Colors.white,
            height: 85,
            padding: const EdgeInsets.only(left: 16, bottom: 2, right: 16),
            child: HomeSearchView(),
          ),
          Container(
            padding: EdgeInsets.fromLTRB(0, 15, 0, 0),
            margin: const EdgeInsets.only(top: 130),
            child: TabBarView(
              controller: _tabController,
              children: pages,
            ),
          ),
          Container(
            margin: const EdgeInsets.only(top: 85),
            child: TabBar(
              controller: _tabController,
              isScrollable: true,
              labelColor: Colors.black,
              labelStyle: TextStyle(fontSize: 18),
              unselectedLabelStyle: TextStyle(fontSize: 14),
              unselectedLabelColor: Colors.black87,
              indicatorColor: Theme.of(context).primaryColor,
              tabs: tabViews,
            ),
          ),
        ],
      ),
    ));
  }
}
